//首页，用于登录和选择功能
import {APPID, SECRET, loginAddress} from '../../utils/settings'
const app = getApp()
Page({
  data: {
    isLogin: false,
    nickName: '',
    avatarUrl: '',
    isNewUser: false,
  },
  //绑定页面跳转
  toPhysicalRecord(){
    wx.switchTab({
      url: '../infoInput/infoInput',
    })
  },
  toScoreInput(){
    wx.switchTab({
      url: '../scoreInput/scoreInput',
    })
  },
  toRecurePlan(){
    wx.switchTab({
      url: '../recurePlan/recurePlan',
    })
  },
  toQuestion(){
    wx.switchTab({
      url: '../question/question',
    })
  },
  toQuestion2(){
    wx.switchTab({
      url: '../question2/question2',
    })
  },
  //退出登录
  toExit(){
    wx.setStorageSync("userInfo", "")
    app.globalData.user.isLogin = false
    this.setData({
      isLogin: false,
      nickName: "",
      avatarUrl: ""
    })
  },
  //登录
  myLogin(){
    wx.login({
      success:(res)=>{
        console.log('请求到登陆凭证:'+res.code)
        wx.request({
          url: 'https://api.weixin.qq.com/sns/jscode2session?appid='+APPID
          +'&secret='+SECRET
          +'&js_code='+res.code+'&grant_type=authorization_code',
          success: (res)=>{
            console.log('请求到openid:'+res.data.openid)
            app.globalData.user.openid = res.data.openid
            //获取到openid后请求获取用户信息
            wx.request({
              url: loginAddress,
              method: 'POST',
              data: {'openid': res.data.openid},
              success:(res2)=>{
                if(res2.data['type'] == 'new'){
                  this.setData({
                    isNewUser: true
                  })
                }
                let userInfo = res2.data
                userInfo['openid'] = res.data.openid
                wx.setStorageSync('userInfo', userInfo)
              },
              fail:(err)=>{
                this.setData({
                  isNewUser: true
                })
                wx.showToast({
                  title: '无法连接到网络',
                  icon: 'error'
                })
                let userInfo = res.data
                wx.setStorageSync('userInfo', userInfo)
              }
            })
            
          }
        })
      }
    })
    // 声明获取用户个人信息后的用途，后续会展示在弹窗中
    wx.getUserProfile({
      desc: '获取你的昵称、头像', 
      success: (res) => {
        console.log("成功请求到个人信息")
        app.globalData.user.nickName = res.userInfo.nickName
        app.globalData.user.avatarUrl = res.userInfo.avatarUrl
        app.globalData.user.isLogin = true
        this.setData({
          isLogin: true,
          nickName: res.userInfo.nickName,
          avatarUrl: res.userInfo.avatarUrl
        })
      },
      fail: (res)=>{
        console.log("请求个人信息失败")
        console.log(res)
      }
    })
    
  },
  onLoad: function (options) {
    this.setData({
      isLogin: app.globalData.user.isLogin,
      nickName: app.globalData.user.nickName,
      avatarUrl: app.globalData.user.avatarUrl
    })
  },

})